<template>
  <el-drawer
    :visible="drawerVisible"
    @close="cancel"
    v-loading="loading"
    size="1000px"
    style="z-index: 2012"
    append-to-body
    :wrapperClosable="false"
  >
    <template v-if="detail">
      <div
        slot="title"
        style="font-size: 28px; font-weight: bold; color: #1a1a1a"
      >
        入库
      </div>
      <div style="padding: 0 20px 40px">
        <el-descriptions :column="1">
          <el-descriptions-item label="门店名称">{{
            shopDetail.shopName || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{
            detail.orderNo
          }}</el-descriptions-item>
          <el-descriptions-item label="手机号码">{{
            detail.customPhone
          }}</el-descriptions-item>
          <el-descriptions-item label="渠道">
            {{ orderComeFromMap[detail.comeFrom] }}</el-descriptions-item
          >
          <el-descriptions-item label="商品信息"
            ><div>
              <div v-for="item in detail.orderGoodPoList">

                      {{ item.name }}

                [{{
                  item.price
                }}]

                <!-- {{ productListMap[item.goodsId]? productListMap[item.goodsId].name:"没有匹配到" }}
                [{{
                  productListMap[item.goodsId]? productListMap[item.goodsId].price:"没有匹配到"
                }}] -->
                
                
                [{{ item.buyNum }}份]
              </div>
            </div></el-descriptions-item
          >
          <el-descriptions-item label="商品总额">
            {{ detail.totalPrice.toFixed(2) }} （元）</el-descriptions-item
          >
          <el-descriptions-item label="订单折扣"
            >{{ detail.discountRatio }}%</el-descriptions-item
          >
          <el-descriptions-item label="订单金额"
            >{{ detail.orderPrice.toFixed(2) }}（元）</el-descriptions-item
          >
          <el-descriptions-item label="物流单号" v-if="detail.comeFrom !== '1'">
            <template v-if="detail.orderTransportPoList">
              <span
                v-for="item in detail.orderTransportPoList"
                style="margin-right: 5px"
              >
                {{ item.wayBillCode }}({{ item.type }})
              </span>
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="鞋子数量" v-if="confirmShoeVisible">
            <el-input
              v-model="confirmShoe.shoeNum"
              placeholder="请输入鞋子数量"
              style="width: 100px; margin-right: 10px"
            ></el-input>
            <el-button type="primary" @click="confirmOrderShoe"
              >生成水洗码</el-button
            >
          </el-descriptions-item>

          <el-descriptions-item label="鞋子数量" v-else>
            {{ detail.shoeNum }}</el-descriptions-item
          >

          <el-descriptions-item label="客户备注">{{
            detail.customerRemark || "-"
          }}</el-descriptions-item>

          <el-descriptions-item label="商家备注">
            <el-input
              type="textarea"
              v-model="detail.shopRemark"
              placeholder="请输入备注"
              style="width: 300px; margin-right: 10px"
            ></el-input>

            <el-button
              size="mini"
              type="primary"
              :loading="updateShopRemarkLoading"
              @click="updateShopRemark"
            >
              更新备注
            </el-button>
          </el-descriptions-item>

          <el-descriptions-item
            label="鞋子信息"
            v-if="detail.shoePoList && detail.shoePoList.length"
          >
            <div style="flex: 1">
              <div
                style="display: flex; justify-content: end; margin-bottom: 20px"
              >
                <template v-if="detail.status === 2 || detail.status === 1">
                  <el-button type="primary" @click="addShoe"
                    >添加鞋子</el-button
                  >
                  <el-button type="primary" @click="photograph">拍照</el-button>
                  <el-button
                    type="primary"
                    @click="temporaryMemory"
                    :loading="temporaryStorageLoading"
                    >信息暂存</el-button
                  >
                </template>
                <el-button type="primary" @click="printWashCode"
                  >打印水洗码</el-button
                >
                <el-button type="primary" @click="printWashCodeAll"
                  >打印全部水洗码</el-button
                >
              </div>
              <el-table
                :data="detail.shoePoList"
                ref="multipleTable"
                 :span-method="objectSpanMethod"
                border
                style="margin-bottom: 20px"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column
                  property="washCode"
                  label="水洗码"
                  width="170"
                ></el-table-column>
                <el-table-column
                  v-if="detail.status === 2 || detail.status === 1"
                  label="类型"
                >
                  <template slot-scope="scope">
                    <el-select
                      v-model="detail.shoePoList[scope.$index].washType"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in washTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="detail.status > 2"
                  property="washType"
                  label="类型"
                ></el-table-column>
                <el-table-column label="状态">
                  <template slot-scope="scope">
                    {{ shoeStatusMap[scope.row.status] }}
                  </template></el-table-column
                >
                <el-table-column
                  property="srgCode"
                  label="货架号"
                ></el-table-column>

                <el-table-column label="图片" width="240">
                  <template slot-scope="scope" v-if="scope.row.picture">
                    <div class="image-box">
                      <div
                        class="image-item"
                        v-for="(item, index) in scope.row.picture"
                      >
                        <i
                          class="el-icon-error"
                          v-if="detail.status === 2"
                          @click="deleteImage(scope.$index, index)"
                        />
                        <el-image
                          style="width: 50px; height: 50px; margin-right: 5px"
                          :src="item.url"
                          :preview-src-list="
                            scope.row.picture.map((item) => item.url)
                          "
                        >
                        </el-image>
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-descriptions-item>

          <el-descriptions-item
            label="鞋子配饰"
            v-if="detail.shoePoList && detail.shoePoList.length"
          >
            <div class="image-box">
              <div class="image-item" v-for="(item, index) in pictureList">
                <i
                  class="el-icon-error"
                  @click="deleteAccImage(index)"
                  v-if="detail.status === 2 || detail.status === 1"
                />
                <el-image
                  style="width: 50px; height: 50px; margin-right: 5px"
                  :src="item.url"
                  :preview-src-list="pictureList.map((item) => item.url)"
                >
                </el-image>
              </div>
            </div>
            <el-button
              type="primary"
              @click="accVisible = true"
              v-if="detail.status === 2 || detail.status === 1"
              >拍照</el-button
            >
          </el-descriptions-item>

          <template v-if="detail.status > 2">
            <el-descriptions-item label="入库时间">{{
              detail.checkInTime
            }}</el-descriptions-item>
            <el-descriptions-item label="入库人">{{
              detail.checkInPerson
            }}</el-descriptions-item>
          </template>
        </el-descriptions>

        <div style="display: flex; justify-content: left; margin-top: 30px">
          <el-button
            style="width: 120px"
            type="primary"
            v-if="
              (detail.status === 2 || detail.status === 1) &&
              detail.shoePoList &&
              detail.shoePoList.length
            "
            @click="submitInStorage"
            :loading="submitLoading"
            >确认</el-button
          >
          <el-button style="width: 120px" @click="cancel">关闭</el-button>
        </div>
      </div>

      <Photograph
        :photographVisible="photographVisible"
        :detail="detail"
        @success="success"
        @close="photographVisible = false"
      />

      <PrintWashCode
        ref="PrintWashCode"
        :customerDetail="customerDetail"
        :multipleSelection="multipleSelection"
        :phone="detail.customPhone"
      />

      <Acc
        :accVisible="accVisible"
        :photos="pictureList"
        @success="accSuccess"
      />
    </template>
  </el-drawer>
</template>

<script>
import Photograph from "@/views/order/inStorage/Photograph/index.vue";
import Acc from "./Acc.vue";
import { getCustomerDetailByPhone } from "@/api/customer/index";
import {
  orderComeFromMap,
  washTypeList,
  IMAGE_OSS_URL,
  BASE_URL,
  shoeStatusMap,
} from "@/config/index";
import {
  shoeInStorage,
  updateShoeType,
  orderAssignShoeRack,
  getOrderDetailByMulType,
  addShoeToOrder,
} from "@/api/order/index";
import { getShopDetail } from "@/api/shop/index";
import { base64DataToFile } from "@/utils/file";
import { getOssClient } from "../../../../utils/tool";
import { v4 as uuidv4 } from "uuid";
import dayjs from "dayjs";
import PrintWashCode from "@/components/PrintWashCode/PrintWashCode.vue";
import { updateOrderShopRemark } from "../../../../api/order";
export default {
  components: {
    Photograph,
    PrintWashCode,
    Acc,
  },
  props: ["drawerVisible", "keywords", "productListMap"],
  data() {
    return {
      BASE_URL,
      IMAGE_OSS_URL,
      detail: false,
      loading: false,
      temporaryStorageLoading: false,
      submitLoading: false,

      shopDetail: {},
      photographVisible: false,
      url: "",
      washTypeList,
      orderComeFromMap,
      shoeStatusMap,

      multipleSelection: [],
      confirmShoeVisible: false,
      confirmShoe: {
        shoeNum: "",
      },
      customerDetail: null,

      pictureList: [],
      accVisible: false,

      updateShopRemarkLoading: false,
    };
  },
  watch: {
    drawerVisible(val) {
      // console.info("请求数据",this.keywords)
      if (val === false) {
        this.detail = false;
        this.$emit("close");
      } else {
        this.getDetail();
      }
    },
  },
  methods: {
   
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {

       // if (columnIndex === 4) {
        //   return {
       //       rowspan: 2,
       //       colspan: 1
       //     };
          // if (rowIndex % 2 === 0) {
          //   return {
          //     rowspan: 2,
          //     colspan: 1
          //   };
          // } else {
          //   return {
          //     rowspan: 0,
          //     colspan: 0
          //   };
          // }
       // }
      
      },


    getDetail() {
      this.loading = true;
      getOrderDetailByMulType(this.keywords)
        .then((res) => {
          res.data.shoePoList.forEach((item, index) => {
            item.picture = item.picture
              ? item.picture.split(",").map((key) => {
                  return {
                    url: IMAGE_OSS_URL + key,
                    status: "success",
                    data: key,
                  };
                })
              : [];
            item.washType =
              item.washType ||
              res.data.orderGoodPoList[0].washType ||
              washTypeList[0].value;

            item.index = `${index + 1}/${res.data.shoePoList.length}`;
          });
          this.pictureList = res.data.fittingImg
            ? res.data.fittingImg.split(",").map((key) => {
                return {
                  url: IMAGE_OSS_URL + key,
                  status: "success",
                  data: key,
                };
              })
            : [];
          this.detail = res.data;
          this.getShopDetail(res.data.shopId);
          this.getCustomerDetail(res.data.customPhone);

          // 如果是线下订单，且订单状态为取鞋中或待入库，且鞋子信息为空
          if (
            res.data.comeFrom !== "1" &&
            (res.data.status === 2 || res.data.status === 1) &&
            (!res.data.shoePoList || res.data.shoePoList.length === 0)
          ) {
            this.confirmShoe.shoeNum = res.data.shoeNum;
            this.confirmShoeVisible = true;
          }
        })
        .then(() => {
          this.loading = false;
        })
        .catch((err) => {
          // console.log(err);
          this.loading = false;
          this.$emit("close");
        });
    },
    getCustomerDetail(phone) {
      getCustomerDetailByPhone(phone).then((res) => {
        this.customerDetail = res.data;
      });
    },
    getShopDetail(id) {
      getShopDetail(id).then((res) => {
        this.shopDetail = res.data;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    photograph() {
      this.photographVisible = true;
    },
    success(datas) {
      datas.forEach((data) => {
        const index = this.detail.shoePoList.findIndex(
          (item) => item.washCode === data.washCode
        );
        this.detail.shoePoList[index].picture = data.picture;
      });
      this.photographVisible = false;
    },
    cancel() {
      this.$emit("close");
    },
    accSuccess(datas) {
      this.pictureList = datas;
      this.accVisible = false;
    },
    printWashCode() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择需要打印的水洗码");
        return;
      }
      const hasEmptyType = this.multipleSelection.some(
        (item) => !item.washType
      );
      if (hasEmptyType) {
        this.$message.error("请选择鞋子类型");
        return;
      }
      this.$refs.PrintWashCode.$refs.printBtn.click();
    },
    printWashCodeAll() {
      this.detail.shoePoList.forEach((item) => {
        this.$refs.multipleTable.toggleRowSelection(item);
      });
      this.$nextTick(() => {
        this.printWashCode();
      });
    },

    async uploadImage() {
      // 等待上传的图片
      const waitUploadImageList = [];
      this.detail.shoePoList
        .filter((item) => {
          return item.picture.some((image) => image.status === "upload");
        })
        .map((item) => {
          item.picture.forEach((image, index) => {
            if (image.status === "upload") {
              waitUploadImageList.push({
                index,
                washCode: item.washCode,
                image: image.url,
              });
            }
          });
          return item;
        });

      const client = await getOssClient();

      const requestList = waitUploadImageList.map((item) => {
        const fileName = `public/img/${dayjs().format(
          "YYYY-MM-DD"
        )}/${uuidv4()}.png`;
        item.efficient = fileName;
        return client.put(fileName, base64DataToFile(item.image));
      });

      const resultList = await Promise.all(requestList);

      resultList.forEach((res, index) => {
        const imageObject = waitUploadImageList[index];
        this.detail.shoePoList
          .find((item) => item.washCode === imageObject.washCode)
          .picture.splice(imageObject.index, 1, {
            url: imageObject.image,
            status: "success",
            data: waitUploadImageList[index].efficient,
          });
      });
    },
    async submitInStorage() {
      const isBadData = this.detail.shoePoList.some(
        (item) => !item.picture || item.picture.length === 0 || !item.washType
      );
      if (isBadData) {
        this.$message.error("请完善鞋子信息");
        return;
      }
      this.submitLoading = true;
      try {
        await this.uploadImage();
      } catch (error) {
        this.submitLoading = false;
        this.$message.error("图片上传失败");
        return;
      }

      const params = {
        orderId: this.detail.id,
        fittingImg: this.pictureList.map((item) => item.data).join(","),
        shoeImgDtoList: this.detail.shoePoList.map((item) => {
          return {
            shoeId: item.id,
            shopRemark: this.detail.shopRemark,
            shoeImg: item.picture.map((image) => image.data).join(","),
            washType: item.washType,
          };
        }),
      };
      shoeInStorage(params)
        .then(() => {
          this.$emit("refresh");
        })
        .finally(() => {
          this.submitLoading = false;
        });
    },
    confirmOrderShoe() {
      if (
        !this.confirmShoe.shoeNum ||
        !/^[1-9]\d*$/.test(this.confirmShoe.shoeNum)
      ) {
        this.$message.error("请输入正确的鞋子数量");
        return;
      }
      const shopId = this.$store.state.user.currentShop.id;
      orderAssignShoeRack(
        this.detail.id,
        this.confirmShoe.shoeNum,
        shopId
      ).then(() => {
        this.confirmShoeVisible = false;
        this.getDetail();
      });
    },
    async temporaryMemory() {
      this.temporaryStorageLoading = true;
      try {
        await this.uploadImage();
      } catch (error) {
        this.temporaryStorageLoading = false;
        this.$message.error("图片上传失败");
        return;
      }
      const params = {
        orderId: this.detail.id,
        fittingImg: this.pictureList.map((item) => item.data).join(","),
        shoeImgDtoList: this.detail.shoePoList.map((item) => {
          return {
            shoeId: item.id,
            shopRemark: this.detail.shopRemark,
            shoeImg: item.picture.map((image) => image.data).join(","),
            washType: item.washType,
          };
        }),
      };
      updateShoeType(params)
        .then(() => {
          this.$message.success("信息暂存成功");
          this.getDetail();
        })
        .finally(() => {
          this.temporaryStorageLoading = false;
        });
    },
    deleteImage($scopeIndex, index) {
      this.detail.shoePoList[$scopeIndex].picture.splice(index, 1);
    },
    deleteAccImage(index) {
      this.pictureList.splice(index, 1);
    },
    addShoe() {
      this.$prompt("请输入添加鞋子数量", "添加鞋子", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: "请输入正确的鞋子数量",
      }).then(({ value }) => {
        addShoeToOrder(this.detail.id, value)
          .then(() => {
            this.$message.success("添加成功");
            this.getDetail();
          })
          .catch(() => {
            this.$message.error("添加失败");
          });
      });
    },
    async updateShopRemark() {
      try {
        this.updateShopRemarkLoading = true;
        await updateOrderShopRemark(this.detail.id, this.detail.shopRemark);
        this.$message.success("更新成功");
      } finally {
        this.updateShopRemarkLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.image-box {
  width: 220px;
  display: flex;
  flex-wrap: wrap;
  .image-item {
    position: relative;
    flex: 0 0 50px;
    &:nth-child(4n) {
      margin-right: 0;
    }
    .el-icon-error {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 1;
      background-color: #ffffff;
      border-radius: 50%;
      cursor: pointer;
    }
  }
}
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
